<?php
defined('IN_IA') or exit('Access Denied');

class vote{

    public $error = '';


    public $integral_user = 'weengine.yilouapp.com';


    public $partner = 'wind.chason.vip';



    /**
     * @param $position
     * @param $limit
     * @return array
     */
    public function getRecommend($position, $limit, $member_id = '')
    {
        $t = time();
        $sql = "SELECT * FROM " . prefix('home') . " WHERE position={$position} AND {$t} > start AND {$t} < end" . get_uniacid() . " ORDER BY sort DESC,id DESC";

        $data = p_fetchall($sql);

        $result = array();

        $end_exhibition = getConfig('end_exhibition', 1);

        if (!empty($data)) {
            foreach ($data as & $value) {
                $a = array();

                $a['type'] = $value['type'];
                $a['relation_id'] = $value['relation_id'];

                if ($value['type'] == 1) {
                    $info = p_get('luck', array('id' => $value['relation_id']));
                    if ($info['status'] > 1 && $end_exhibition == 1) {
                        continue;
                    }

                    $a['is_senior'] = $info['is_senior'];
                    $a['goods'] = p_getall('luck_goods', array('luck_id' => $info['id']));

                    $a['image'] = $value['image'] ? getImage($value['image']) : (getImage($a['goods'][0]['image'] ? $a['goods'][0]['image'] : getConfig('prize_default_picture')) ? : '');
                    $a['sponsor'] = $info['sponsor'];

                    if ($info['lottery_type'] == 1) {
                        $a['lottery'] = date('m月d日 H:i', $info['lottery_value']);
                    } elseif ($info['lottery_type'] == 2) {
                        $a['lottery'] = '满' . $info['lottery_value'] . '人';
                    } else {
                        $a['lottery'] = '发起者手动开奖';
                    }
                    $a['member'] = p_get('memberinfo', array('id' => $info['member_id']));
                    $a['luck_mode'] = $info['luck_mode'];
                    $a['lottery_type'] = $info['lottery_type'];
                    $a['senior_source'] = $info['senior_source'];

                    $a['prize_type'] = ($a['senior_source'] == 1 && $a['is_senior'] == 2) ? 2 : 1;

                    $a['is_apply'] = p_getcolumn('luck_participate', array('luck_id' => $value['relation_id'], 'member_id' => $member_id), 'COUNT(*)') > 0;
                } else {
                    $info = p_get('vote_activity', array('id' => $value['relation_id']));
                    //$a['goods'] = p_getall('vote_goods', array('vote_id' => $info['id']));
                    if ($info['vote_status'] > 1 && $end_exhibition == 1) {
                        continue;
                    }

                    $a['image'] = $value['image'] ? getImage($value['image']) : getVoteImageCover($info);

                    $a['sponsor'] = $info['sponsor_name'];
                    $a['member'] = p_get('memberinfo', array('id' => $info['member_id']));
                    $a['is_apply'] = p_getcolumn('vote_join', array('activity_id' => $value['relation_id'], 'uid' => $member_id), 'COUNT(*)') > 0;
                    $a['senior_source'] = $info['prize_type'];
                    $a['end_time'] =  date('Y-m-d H:i', $info['end_time']). ' 结束';
                    $a['vote_title'] = $info['title'];
                    $a['join_num'] = $info['join_num'];
                    $a['vote_num'] = $info['vote_num'];
                    $a['prize_type'] = $info['prize_type'];
                }
                //$a['image'] = getImage($value['image']);
                $result[] = $a;
            }
        }

        return $result;
    }


    /**
     * @param $position
     * @param array $limit
     * @return array|mixed
     */
    public function getAdvertisement($position, $limit = array())
    {
        if (in_array($position, array(1, 2, 3, 4))) {
            return ad(p_get('advertisement', array('position' => $position)));
        } else {
            $ad = p_getall('advertisement', array('position' => $position), array(), '', array('sort desc'), $limit);

            return empty($ad) ? array() : array_map('ad', $ad);
        }
    }


    /**
     * @param $shop_id
     * @param $position
     * @param array $limit
     * @return array|mixed
     */
    public function getShopAd($shop_id, $position, $limit = array())
    {
        if (in_array($position, array(2))) {
            return ad(p_get('shop_advertisement', array('shop_id' => $shop_id, 'position' => $position)));
        } else {
            $ad = p_getall('shop_advertisement', array('shop_id' => $shop_id,'position' => $position), array(), '', array('sort desc'), $limit);

            return empty($ad) ? array() : array_map('ad', $ad);
        }
    }


    /**
     * @param $obj
     * @return bool
     */
    public function isShare($obj)
    {
        $n = array(
            'noLogin' => array('login'),
            'index' => array('register'),
            'goods' => array('goods', 'search'),
            'user' => array('setAddress', 'authStart3'),
            'luck' => array('create', 'participate', 'lottery', 'participant', 'complaint'),
            'senior' => array('givingConfirm'),
            'bhCommon' => array('activation', 'myHome'),
            'cvote' => array('getBomb', 'vote', 'complaint', 'detail', 'signup', 'delete', 'addJoin', 'administration', 'checkList', 'joinDetails', 'addBomb'),
            'shop' => array('getShop', 'index', 'goods', 'updateStep', 'suspension', 'receive', 'details', 'signin', 'signin_details'),
        );

        return isset($n[$obj->contr]) && in_array($obj->action, $n[$obj->contr]);
    }


    /**
     * @param $member_id
     * @param $money
     * @param $relation_id
     * @param int $type
     * @return bool|string
     */
    public function unifiedOrder($member_id, $money, $relation_id, $type = 1)
    {
        $trade_no = date("YmdHis", time()) . $member_id . mt_rand(10000, 99999);
        $pay = array(
            'member_id' => $member_id,
            'trade_no' => $trade_no,
            'money' => $money,
            'relation_id' => $relation_id,
            'type' => $type,
            'created' => time()
        );

        if (p_insert('pay_order', $pay)) {
            return $trade_no;
        }
        return false;
    }


    /**
     * @param $id
     * @param $goods_name
     * @param $goods_image
     * @param $number
     * @param int $type
     * @param array $fictitious
     * @return bool
     * @throws Exception
     */
    public function addVoteGoods($id, $goods_name, $goods_image, $number, $type = 1, $fictitious = array())
    {
        $luck = p_get('luck', array('id' => $id));

        $i = array(
            'luck_id' => $luck['id'],
            'member_id' => $luck['member_id'],
            'type' => $type,
            'name' => $goods_name,
            'image' => $goods_image,
            'number' => $number,
            'source' => 1,
            'created' => time()
        );

        if ($luck['luck_mode'] == 2 && ($i['number'] % $luck['team_number'] > 0)) {
            $this->error = '奖品数量必须为成团人数的整数倍';
            return false;
        }

        if ($type == 2) {
            $i['number'] = count($fictitious);
            $i['fictitious'] = json_encode($fictitious);
        }


        if (!p_insert('luck_goods', $i)) {
            $this->error = '添加商品失败';
            return false;
        }
        $pid = pdo_insertid();

        if (!p_update('luck', array('prize_number' => $luck['prize_number'] + $i['number']), array('id' => $luck['id']))) {
            $this->error = '添加商品失败';
            return false;
        }

        return $this->createPrize($i, $pid);
    }




    /**
     * @param $id
     * @return bool
     */
    public function create($id)
    {
        $luck = p_get('luck', array('id' => $id));
        if (empty($luck) || $luck['complete'] != 1) {
            return true;
        }
        $goods = json_decode($luck['goods'], true);

        pdo_begin();
        try{
            $number = 0;
            if ($luck['is_senior'] == 2 && $luck['senior_source'] == 1) {
                foreach ($goods as $value) {
                    $number += $value['number'];
                    $g = p_get('goods', array('id' => $value['id']));
                    $i = array(
                        'luck_id' => $id,
                        'member_id' => $luck['member_id'],
                        'type' => 1,
                        'name' => $g['name'],
                        'image' => $g['cover_image'],
                        'number' => $value['number'],
                        'source' => 2,
                        'goods_id' => $value['id'],
                        'created' => time()
                    );
                    if (!p_insert('luck_goods', $i)) {
                        throw new Exception('发起失败');
                    }
                    if (!$this->createPrize($i, pdo_insertid())) {
                        throw new Exception($this->error);
                    }
                }
            } else {
                if ($luck['is_senior'] == 2 && $luck['senior_source'] == 2 && getConfig('open_senior') != 2) {
                    if (!$this->change_senior($luck['member_id'], 1, 2)) {
                        throw new Exception($this->error);
                    }
                }

                foreach ($goods as $value) {

                    $i = array(
                        'luck_id' => $id,
                        'member_id' => $luck['member_id'],
                        'type' => $value['type'],
                        'name' => $value['name'],
                        'image' => $value['image'],
                        'number' => $value['number'],
                        'source' => 1,
                        'created' => time()
                    );
                    if ($value['type'] == 2) {
                        $i['fictitious'] = json_encode($value['fictitious']);
                        $i['number'] = count($value['fictitious']);
                        $number += $i['number'];
                    } else {
                        $number += $value['number'];
                    }
                    if (!p_insert('luck_goods', $i)) {
                        throw new Exception('发起失败');
                    }
                    if (!$this->createPrize($i, pdo_insertid())) {
                        throw new Exception($this->error);
                    }
                }
            }

            if (!p_update('luck', array('complete' => 2, 'prize_number' => $number), array('id' => $id, 'complete' => 1))) {
                throw new Exception('发起失败');
            }
            pdo_commit();



            return true;
        } catch (Exception $e) {
            pdo_rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }


    /**
     * @param $data
     * @return bool
     */
    public function createPrize($data, $luck_goods_id)
    {
        $number = $data['number'];
        unset($data['number']);
        $data['luck_goods_id'] = $luck_goods_id;

        if ($data['type'] == 1) {
            for ($i = 0; $i < $number; $i++) {
                if (!p_insert('luck_goods_info', $data)) {
                    $this->error = '发起失败';
                    return false;
                }
            }
        } else {
            $fictitious = json_decode($data['fictitious']);
            unset($data['fictitious']);
            foreach ($fictitious as $value) {
                $data['fictitious'] = $value;
                if (!p_insert('luck_goods_info', $data)) {
                    $this->error = '发起失败';
                    return false;
                }
            }
        }

        return true;
    }


    /**
     *
     */
    public function change_senior($member_id, $number = 1, $type = 1, $remarks = '')
    {
        $senior_member = p_get('senior_member', array('member_id' => $member_id));
        if ($type == 2 && (empty($senior_member) || $senior_member['number'] < $number)) {
            $this->error = '高级版可使用的数量不足,请先购买';
            return false;
        }

        try{

            if (in_array($type, array(1, 4, 5))) {
                if (empty($senior_member)) {
                    $insert = array(
                        'member_id' => $member_id,
                        'number' => $number,
                        'created' => time()
                    );
                    if (!p_insert('senior_member', $insert)) {
                        throw new Exception('高级版本数量变更失败');
                    }
                } else {
                    $update = array(
                        'number' => $senior_member['number'] + $number,
                    );
                }

            } else {
                $update = array('number' => $senior_member['number'] - $number);
            }

            if (isset($update) && !p_update('senior_member', $update, array('id' => $senior_member['id']))) {
                throw new Exception('高级版本数量变更失败');
            }
            $insert = array(
                'member_id' => $member_id,
                'number' => $number,
                'type' => $type,
                'created' => time()
            );
            if (!empty($remarks)) {
                $insert['remarks'] = $remarks;
            }
            if (!p_insert('senior_member_log', $insert)) {
                throw new Exception('高级版本数量变更失败');
            }
            return true;
        } catch (Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }


    /**
     * @param $id
     * @return bool
     */
    public function lottery($id)
    {
        $luck = p_get('luck', array('id' => $id, 'complete' => 2, 'is_delete' => 1, 'status' => 1));
        if (empty($luck)) {
            $this->error = '该抽奖不存在';
            return false;
        }

        $count = p_getcolumn('luck_participate', array('luck_id' => $id), 'COUNT(*)') ? : 0;

        if ($count < $luck['prize_number']) {
            p_update('luck', array('status' => 3, 'lottery_time' => time(), 'send_msg' => 2) , array('id' => $id));
            return true;
        }
        $bargain = new bargain();

        pdo_begin();
        try{
            if ($luck['luck_mode'] != 2 && $luck['luck_mode'] != 3) {
                $prize = p_getall('luck_goods_info', array('luck_id' => $id));
                $in_prize = array();
                foreach ($prize as $value) {
                    if ($value['is_appoint'] == 2) {
                        $participate = p_get('luck_participate', array('id' => $value['appoint_id']));
                        $in_prize[] = $value['appoint_id'];
                    } else {
                        $notIn = '';
                        if ($in_prize) {
                            $notIn = 'AND id NOT IN (' . implode(',', $in_prize) . ')';
                        }
                        $sql = "SELECT * FROM " . prefix('luck_participate') . " WHERE luck_id={$id} " . $notIn . ' order by rand() LIMIT 1';
                        $participate = p_fetch($sql);
                        $in_prize[] = $participate['id'];
                    }

                    if (!p_update('luck_goods_info', array('in_member_id' => $participate['member_id']), array('id' => $value['id']))) {
                        throw new Exception('开奖失败1');
                    }

                    if (!p_update('luck_participate', array('in_prize' => 2, 'goods_info_id' => $value['id']), array('id' => $participate['id']))) {
                        throw new Exception('开奖失败2');
                    }

                    if ($value['type'] == 3) {
                        if (!$bargain->change_money($participate['member_id'], $value['money'], 4)) {
                            throw new Exception($this->error);
                        }
                    }
                }
            } else if ($luck['luck_mode'] == 2){
                $goods = p_getall('luck_goods', array('luck_id' => $id));
                $new_goods = array();

                $goods_infos = array();
                foreach ($goods as $val) {
                    $new_goods[$val['id']] = $val;
                    $goods_infos[$val['id']] = p_getall('luck_goods_info', array('luck_goods_id' => $val['id']));
                }


                $appoint = p_getall('luck_group', array('luck_id' => $id, 'current_number' => $luck['team_number'], 'is_appoint' => 2, 'in_prize' => 1));
                if ($appoint) {
                    foreach ($appoint as $value) {
                        if (isset($new_goods[$value['appoint_goods_id']])
                            && $new_goods[$value['appoint_goods_id']]['number'] > 0
                            && $goods_infos[$value['appoint_goods_id']]
                        ) {
                            $g = $new_goods[$value['appoint_goods_id']];
                            $join = p_getall('luck_participate', array('group_id' => $value['id']));
                            foreach ($join as $val) {
                                if (!p_update('luck_participate', array('in_prize' => 2, 'goods_info_id' => $goods_infos[$g['id']][0]['id']), array('id' => $val['id']))) {
                                    throw new Exception('开奖失败3');
                                }
                                $new_goods[$value['appoint_goods_id']]['number'] -- ;
                                if (!p_update('luck_goods_info', array('in_member_id' => $val['member_id']), array('id' => $goods_infos[$g['id']][0]['id']))) {
                                    throw new Exception('开奖失败7');
                                }
                                array_shift($goods_infos[$g['id']]);
                            }

                            if (!p_update('luck_group', array('in_prize' => 2, 'luck_goods_id' => $g['id']), array('id' => $value['id']))) {
                                throw new Exception('开奖失败4');
                            }
                            if ($new_goods[$value['appoint_goods_id']]['number'] < 1) {
                                unset($new_goods[$value['appoint_goods_id']]);
                            }
                        }
                    }
                }

                if ($new_goods) {
                    $number = 0;
                    $new = array();
                    foreach ($new_goods as $line) {
                        $number += $line['number'];
                        $new[] = $line;
                    }
                    $limit = intval($number / $luck['team_number']);
                    if ($limit >= 1) {
                        $sql = "SELECT * FROM " . prefix('luck_group') . " WHERE luck_id = {$id} AND current_number={$luck['team_number']} AND in_prize = 1 AND is_appoint = 1 ORDER BY RAND() LIMIT {$limit}";
                        $data = p_fetchall($sql);
                        if ($data) {
                            foreach ($data as $v) {
                                $join = p_getall('luck_participate', array('group_id' => $v['id']));
                                $g = $new[0];

                                if ($goods_infos[$g['id']]) {
                                    foreach ($join as $val) {
                                        if (!p_update('luck_participate', array('in_prize' => 2, 'goods_info_id' => $goods_infos[$g['id']][0]['id']), array('id' => $val['id']))) {
                                            throw new Exception('开奖失败5');
                                        }
                                        $new[0]['number'] --;
                                        if (!p_update('luck_goods_info', array('in_member_id' => $val['member_id']), array('id' => $goods_infos[$g['id']][0]['id']))) {
                                            throw new Exception('开奖失败7');
                                        }
                                        array_shift($goods_infos[$g['id']]);
                                    }

                                }
                                if (!p_update('luck_group', array('in_prize' => 2, 'luck_goods_id' => $g['id']), array('id' => $v['id']))) {
                                    throw new Exception('开奖失败6');
                                }
                                if ($new[0]['number'] < 1) {
                                    array_shift($new);
                                }
                            }
                        }
                    }
                }
            } else {

                $prize = p_getall('luck_goods_info', array('luck_id' => $id));
                $in_member = array();
                foreach ($prize as $value) {
                    if ($value['is_appoint'] == 2) {
                        $participate = p_get('luck_participate', array('id' => $value['appoint_id']));
                        $in_member[] = $value['member_id'];
                    } else {
                        $notIn = '';
                        if ($in_member) {
                            $notIn = 'AND member_id NOT IN (' . implode(',', $in_member) . ')';
                        }
                        $sql = "SELECT * FROM " . prefix('luck_code') . " WHERE luck_id={$id} " . $notIn . ' order by rand() LIMIT 1';
                        $code = p_fetch($sql);

                        $participate = p_get('luck_participate', array('luck_id' => $id, 'member_id' => $code['member_id']));

                        $in_member[] = $code['member_id'];
                    }

                    if (!p_update('luck_goods_info', array('in_member_id' => $participate['member_id']), array('id' => $value['id']))) {
                        throw new Exception('开奖失败1');
                    }

                    if (!p_update('luck_participate', array('in_prize' => 2, 'goods_info_id' => $value['id']), array('id' => $participate['id']))) {
                        throw new Exception('开奖失败2');
                    }
                    if ($value['type'] == 3) {
                        if (!$bargain->change_money($participate['member_id'], $value['money'], 4)) {
                            throw new Exception($this->error);
                        }
                    }

                }

            }

            if (!p_update('luck',  array('status' => 2, 'lottery_time' => time(), 'send_msg' => 2) , array('id' => $id))) {
                throw new Exception('开奖失败9');
            }

            pdo_commit();

            $luck['loop'] == 2 && $this->automaticArize($id);

            return true;
        } catch (Exception $e) {
            $this->error = $e->getMessage();
            pdo_rollback();
            return false;
        }
    }


    /**
     * @param $id
     * @return bool
     */
    public function luck_info($id, $obj)
    {
        $luck = p_get('luck', array('id' => $id, 'is_delete' => 1, 'complete' => 2));
        if (!empty($luck)) {
            $goods = p_getall('luck_goods', array('luck_id' => $id));
            foreach ($goods as & $value) {
                $value['image'] = getImage($value['image']) ? : $obj->images('prize_default_picture', 'prize_default_picture.png');
            }
            $luck['goods'] = $goods;
        }

        return $luck;
    }


    /**
     * @param $luck_id
     * @param $obj
     * @return array|string
     */
    public function getShaerImg($luck_id, $obj)
    {
        $path = createFile($obj, 'share');
        $name = $luck_id .'.png';

        if (!is_file($path . $name)) {
            if (!$luck = p_get('luck', array('id' => $luck_id))) {
                return '';
            }
            include IA_ROOT . '/addons/bh_vote/lib/Image.class.php';

            $luck_goods = p_get('luck_goods', array('luck_id' => $luck_id), array(), '', 'id desc');
            $luck = p_get('luck', array('id' => $luck_id));

            if ($luck_goods['image']) {
                $image = getImageLocal($obj, $luck_goods['image'], true);
            } else {
                $image = getConfig('prize_default_picture');
                if ($image) {
                    $image = getImageLocal($obj, $image, true);
                } else {
                    $image = array(
                        'path' => IA_ROOT . '/addons/bh_vote/template/static/images/xcx/prize_default_picture.png'
                    );
                }
            }


            $im = imagecreatetruecolor(240, 160);

            $color = imagecolorallocate($im, 255, 255, 255);
            imagefill($im, 0, 0, $color);

            $font_file = IA_ROOT . '/addons/bh_vote/template/static/font/Sun-ExtA.ttf';

            //设定字体的颜色
            $font_color_1 = ImageColorAllocate ($im, 120, 120, 120);
            $font_color_2 = ImageColorAllocate ($im, 28, 28, 28);

            list($g_w,$g_h) = getimagesize($image['path']);
            $goodImg = createImageFromFile($image['path']);
            imagecopyresized($im, $goodImg, 0, 0, 0, 0, 240, 120, $g_w, $g_h);

            //商品描述
            $font = '奖品: ' . $luck_goods['name'];
            $font = $luck_goods['number'] < $luck['prize_number'] ? ($font . ' 等') : $font;
            $theTitle = cn_row_substr($font,2,19);
            imagettftext($im, 11,0, 8, 138, $font_color_2 ,$font_file, $theTitle[1]);

            if ($luck['lottery_type'] == 1) {
                $font_text = date('m月d日 H:i', $luck['lottery_value']) . ' 自动开奖';
            } elseif ($luck['lottery_type'] == 2) {
                $font_text = '满' . $luck['lottery_value'] . '人 自动开奖';
            } else {
                $font_text = '发起者手动开奖';
            }

            imagettftext($im, 9,0, 8, 155, $font_color_1 ,$font_file, $font_text);

            imagepng ($im, $path . $name);

            imagedestroy($im);
            imagedestroy($goodImg);
        }

        return array(
            'url' => $obj->w['siteroot'] . 'attachment/xcx' . $obj->w['uniacid'] . 'share/' . $name,
            'path' => $path . $name
        );
    }



    /**
     * @param $obj
     * @param $param
     * @param $path
     * @param $path_name
     * @return string
     */
    public function createWxCode($obj, $param, $path, $path_name)
    {
        $qrpath = createFile($obj, 'code') . $path_name;

        if (!is_file($qrpath)) {
            include_once IA_ROOT . "/addons/bh_bargain/lib/Gd.class.php";
            include_once IA_ROOT . "/addons/bh_bargain/lib/Image.class.php";

            $Image = new Image();

            $option = array(
                'appid' => $obj->w['uniaccount']['key'],
                'secret' => $obj->w['uniaccount']['secret'],
            );

            $wxObj = new Wxadoc($option);
            $res = $wxObj->createwxaqrcode($param, $path, 430, false, array('r' => 72, 'g' => 145, 'b' => 92));
            if ($res) {
                $qr_temp = ATTACHMENT_ROOT . 'qr_temp' . $obj->member['id'] . '.jpg';

                file_put_contents($qr_temp, $res);
                $qrimg = $Image->open($qr_temp);
                $qrimg->thumb(217, 217)->save($qrpath);

                unlink($qr_temp);
            }
        }

        return $obj->w['siteroot'] . 'attachment/xcx' . $obj->w['uniacid'] .'code/' . $path_name;
    }


    /**
     * @param $id
     * @return bool
     */
    public function voteCreate($id)
    {
        if (!$vote = p_get('vote_activity', array('id' => $id, 'complete' => 1))) {
            return true;
        }

        $joins = json_decode($vote['joins'], true);
        $prize = json_decode($vote['prize'], true);
        pdo_begin();
        try{
            if ($joins) {
                foreach ($joins as $value) {
                    $join = array(
                        'name' => $value['intro'],
                        'status' => 1,
                        'activity_id' => $id,
                        'type' => 1,
                        'is_img' => $vote['type'],
                        'c_time' => time()
                    );
                    if ($vote['type'] == 1) {
                        $join['thumb'] = json_encode(array($value['thumb']));
                        $join['share_thumb'] = $value['share_thumb'];
                    }
                    if (!p_insert('vote_join', $join)) {
                        throw new Exception('发起失败');
                    }
                }
            }

            foreach ($prize as $value) {
                $insert = array(
                    'vote_id' => $id,
                    'member_id' => $vote['member_id'],
                    'name' => $value['name'],
                    'number' => $value['number'],
                    'image' => $value['path'],
                    'source' => $vote['prize_type'],
                    'created' => time()
                );
                if ($vote['prize_type'] == 1) {
                    $insert['image'] = $value['path'];
                } else {
                    $goods = p_get('goods', array('id' => $value['id']));
                    $insert['image'] = $goods['cover_image'];
                    $insert['goods_id'] = $value['id'];
                }
                if (!p_insert('vote_goods', $insert)) {
                    throw new Exception('发起失败');
                }
                $insert['vote_goods_id'] = pdo_insertid();
                unset($insert['number']);

                for ($i = 0; $i < $value['number']; $i++) {
                    if (!p_insert('vote_goods_info', $insert)) {
                        throw new Exception('发起失败');
                    }
                }
            }

            if (!p_update('vote_activity', array('join_num' => count($joins), 'complete' => 2, 'status' => (getConfig('vote_examine', 2) ? : 2)), array('id' => $id))) {
                throw new Exception('发起失败');
            }

            if ($vote['member_id'] > 0) {
                $memberinfo = p_get('memberinfo', array('id' => $vote['member_id']));
                p_update('memberinfo', array('activity_fq_num' => $memberinfo['activity_fq_num'] + 1), array('id' => $vote['member_id']));

            }

            pdo_commit();

            return true;
        } catch (Exception $e){
            $this->error = $e->getMessage();
            pdo_rollback();
            return false;
        }
    }


    /**
     * @param $id
     * @return bool
     */
    public function endVote($id)
    {
        $vote = p_get('vote_activity', array('id' => $id, 'complete' => 2, 'is_delete' => 1));
        if (empty($vote)) {
            return true;
        }

        $prize = p_getall('vote_goods_info', array('vote_id' => $id));

        $num = count($prize);
        if ($vote['lottery_type'] == 1) {
            $in_prize = p_getall('vote_join', array('activity_id' => $id), array(), '', 'vote_num desc', $num);
        } else {
            $sql = 'SELECT * FROM ' . prefix('vote_join') . ' WHERE activity_id=' . $id . ' ORDER BY rand() LIMIT ' . $num;
            $in_prize = p_fetchall($sql);
        }
        pdo_begin();
        try{
            foreach ($prize as $k => $value) {
                if (!isset($in_prize[$k])) {
                    break;
                }
                $update = array(
                    'in_member_id' => $in_prize[$k]['uid'],
                    'join_id' => $in_prize[$k]['id']
                );
                if (!p_update('vote_goods_info', $update, array('id' => $value['id']))) {
                    throw new Exception('操作失败');
                }

                if (!p_update('vote_join', array('in_prize' => 2), array('id' => $in_prize[$k]['id']))) {
                    throw new Exception('操作失败');
                }
            }
            if (!p_update('vote_activity', array('vote_status' => 2), array('id' => $id))) {
                throw new Exception('操作失败');
            }
            pdo_commit();
        } catch (Exception $e) {
            pdo_rollback();
        }

        return true;
    }


    /**
     * @param $member_id
     * @param $code
     * @return bool
     */
    public function checkcaptcha($member_id, $code)
    {
        global $_W;

        $codehash = md5(strtolower($code) . $_W['config']['setting']['authkey']);
        $res = p_get('code', array('member_id' => $member_id));
        if (empty($res) || $res['created'] - time() > 300) {
            $this->error = '验证码已经过期';
            return false;
        }
        if ($codehash != $res['code']) {
            $this->error = '验证码错误';
            return false;
        }
        p_delete('code', array('id' => $res['id']));

        return true;
    }



    /**
     * 生成抽奖码
     * @param $member_id
     * @param $luck_id
     * @param int $invitation_member_id
     * @return bool
     */
    public function create_luck_code($member_id, $luck_id, $invitation_member_id = 0)
    {
        $data = array(
            'member_id' => $member_id,
            'luck_id' => $luck_id,
            'code' => $this->generate_code($luck_id),
            'created' => time()
        );

        if (!p_insert('luck_code', $data)) {
            $this->error = '生成抽奖码失败';
            return false;
        }

        if ($invitation_member_id > 0
            && $invitation_member_id != $member_id
            && p_get('luck_participate', array('luck_id' => $luck_id, 'member_id' => $invitation_member_id))
        ) {
            $data = array(
                'member_id' => $invitation_member_id,
                'luck_id' => $luck_id,
                'invitation_member_id' => $member_id,
                'type' => 2,
                'code' => $this->generate_code($luck_id),
                'created' => time()
            );
            if (!p_insert('luck_code', $data)) {
                $this->error = '生成抽奖码失败';
                return false;
            }
        }

        return true;
    }


    /**
     * @return string
     */
    public function generate_code($luck_id)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        while (true) {
            for($i=0; $i<10; $i++){
                $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
            }
            if (!p_get('luck_code', array('luck_id' => $luck_id,'invitation_code' => $str))) {
                return $str;
            }
        }
    }


    /**
     *  随机字符串
     */
    public function out_trade_no()
    {
        $date = date('Ymd');
        $rand = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))),0,12);
        return $date . $rand . $this->getIssueNumber(12);
    }


    /**
     * @param $length
     * @return string
     */
    protected function getIssueNumber($length)
    {
        $str ='201812345678ab998c76541d230e7899a638k527d411236987412';
        $len =strlen($str)-1;
        $randStr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randStr .= $str[$num];
        }
        return $randStr;
    }


    public function is_integral_plugin()
    {

        $name = 'bh_vote_plugin_integral';
        $plugin_module = WeUtility::createModuleHook($name);

        if ($this->isPlugin()) {
            return true;
        }

        if (empty($plugin_module)) {
            return false;
        }
        $plugin_module = json_decode(json_encode(WeUtility::createModuleHook($name)),true);

        return !isset($plugin_module[$name]['module']['is_delete']);
    }


    public function is_show_integral()
    {
        if (getConfig('sigin_plug_status', 1) == 2) {
            return false;
        }
        return $this->is_integral_plugin();
    }


    public function isPlugin()
    {
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        $urls = array(
            's.gbbdj.com'
        );
        return in_array($basename['basename'], $urls);
    }


    /**
     * 获取签到天数
     * @param $member_id
     * @return int
     */
    public function get_signin($member_id)
    {
        $signin = p_get('signin', array('member_id' => $member_id));
        if (empty($signin)) {
            return 0;
        }

        if ($signin['updated'] > strtotime(date('Y-m-d', time())) - 86400) {
            return $signin['days'];
        }
        return 0;
    }


    /**
     * 某天是否签到
     * @param int $member_id
     * @param string $same_day
     * @return bool
     */
    public function is_sign($member_id, $same_day = '')
    {
        if (empty($same_day)) {
            $same_day = strtotime(date('Y-m-d'));
        }
        return p_getcolumn('integral_log', array('member_id' => $member_id, 'same_day' => $same_day, 'type' => 1), 'COUNT(*)') > 0;
    }


    /**
     * 某天是否签到翻倍
     * @param int $member_id
     * @param string $same_day
     * @return bool
     */
    public function is_sign_double($member_id, $same_day = '')
    {
        if (empty($same_day)) {
            $same_day = strtotime(date('Y-m-d'));
        }
        return p_getcolumn('integral_log', array('member_id' => $member_id, 'same_day' => $same_day, 'type' => 2), 'COUNT(*)') > 0;
    }


    /**
     * 签到
     * @param $member_id
     * @return bool|int
     */
    public function signin($member_id, $integral)
    {
        try {
            pdo_begin();
            $sigin = p_get('signin', array('member_id' => $member_id));

            if (empty($sigin)) {
                $insert = array(
                    'member_id' => $member_id,
                    'days' => 1,
                    'all_sigin' => 1,
                    'updated' => time(),
                    'created' => time()
                );
                if (!p_insert('signin', $insert)) {
                    throw new Exception('签到失败,稍后再试');
                }
                $days = 1;
            } else {

                $today = strtotime(date('Y-m-d', time()));
                if ($sigin['updated'] >= $today) {
                    return $sigin['days'];
                }
                $update = array(
                    'all_sigin' => $sigin['all_sigin'] + 1,
                    'updated' => time()
                );
                if ($sigin['updated'] >= $today - 86400) {
                    $update['days'] = $sigin['days'] + 1;
                } else {
                    $update['days'] = 1;
                }

                if (!p_update('signin', $update, array('id' => $sigin['id']))) {
                    throw new Exception('签到失败,稍后再试');
                }
                $days = $update['days'];
            }

            if (!$this->change_integral($member_id, $integral, 1)) {
                throw new Exception($this->error);
            }
            pdo_commit();
            return $days;
        } catch (Exception $e) {
            pdo_rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }




    /**
     * 积分变动
     * @param $member_id
     * @param $integral
     * @param int $type
     * @param string $remarks
     * @param string $rise_time
     * @return bool
     */
    public function change_integral($member_id, $integral, $type = 1, $remarks = '', $rise_time = '')
    {
        if ($integral <= 0) {
            return true;
        }
        $integral_name = getConfig('integral_name', '积分');
        $member = p_get('memberinfo', array('id' => $member_id));
        if (in_array($type, array(1, 2, 4, 5))) {
            $after_integral = $member['integral'] + $integral;
        } else {

            if (intval($member['integral'] * 100) < intval($integral * 100)) {
                $this->error = $integral_name . '不足';
                return false;
            }
            $after_integral = (intval($member['integral'] * 100) - intval($integral * 100)) / 100;
        }

        $update = array('integral' => $after_integral);
        if (!p_update('memberinfo', $update, array('id' => $member_id))) {
            $this->error = $integral_name . '变动失败';
            return false;
        }

        $integral_log = array(
            'member_id' => $member_id,
            'integral' => $integral,
            'after_integral' => $after_integral,
            'type' => $type,
            'same_day' => strtotime(date('Y-m-d')),
            'created' => $rise_time ? $rise_time : time()
        );
        if ($remarks) {
            $integral_log['remarks'] = $remarks;
        }
        if (p_insert('integral_log', $integral_log)) {
            return true;
        }

        $this->error = $integral_name . '日志更新出错';
        return false;
    }


    public function isIntegralUser()
    {
        return false;
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        return $this->integral_user == $basename['basename'];
    }



    public function partner()
    {
        global  $_W;
        $basename = pathinfo($_W['siteroot']);
        return $this->partner == $basename['basename'];
    }
    /**
     * @param $start
     * @return int|string
     */
    public function automatic_number($start)
    {
        $t =  time() - $start;
        $t = floor($t / 60);
        $automatic_minute = getConfig('automatic_minute', 0);

        if ($automatic_minute < 1 || $t < 1) {
            return 0;
        }
        return $automatic_minute * $t;
    }




    public function automaticArize($id)
    {
        $luck = p_get('luck', array('id' => $id));
        if ($luck['loop'] ==1) {
            return true;
        }
        unset($luck['id']);
        $current = time();
        if ($luck['lottery_type'] == 1) {
            $mistiming = $luck['lottery_value'] - $luck['created'];
            $luck['lottery_value'] = $current + $mistiming;

        }
        $luck['created'] = $current;
        $luck['status'] =1;
        $luck['complete'] =2;
        $luck['is_delete'] =1;
        if (p_insert('luck', $luck)) {
            $luck_id = p_insert_id();
            if ($luckGoods = p_getall('luck_goods', array('luck_id' => $id))) {
                foreach ($luckGoods as & $val) {
                    unset($val['id']);
                    $val['luck_id'] = $luck_id;
                    p_insert('luck_goods', $val);
                }

            }

            if ($luckGoodsInfo = p_getall('luck_goods_info', array('luck_id' => $id))) {
                foreach ($luckGoodsInfo as & $value) {
                    unset($value['id']);
                    $value['in_member_id'] = 0;
                    $value['luck_id'] = $luck_id;
                    $value['is_appoint'] = 1;
                    $value['appoint_id'] = 0;
                    p_insert('luck_goods_info', $value);
                }
            }


        }
        return true;
    }


}